# coding: utf-8

import time
import requests
import csv

URL = 'http://web.meishuquan.net/rest/user/get-user?user_id={}'


def run():
    user_ids = range(300000, 350000)
    get_users(user_ids)


def get_users(user_ids):
    # print 'get_users'
    filename = 'user_{}to{}.csv'.format(user_ids[0], user_ids[-1])
    path = '/tmp/{}'.format(filename)

    for index, user_id in enumerate(user_ids):
        try:
            user_data = get_user(user_id)
            if not user_data:
                continue
            with open(path, 'ab+') as f:
                writer = csv.writer(f)
                row_data = [v if type(v) is not unicode else v.encode('utf-8') for v in user_data.itervalues()]
                writer.writerow(row_data)
            time.sleep(1)
            print 'success'
        except:
            print 'fail'
            pass


def get_user(user_id):
    print 'get_user', user_id
    url = URL.format(user_id)
    r = requests.get(url)
    d = r.json()
    if d['option']['status'] == 0:
        # print 'status == 0'
        return d['data']
    # print 'status != 0'
    return False


if __name__ == '__main__':
    run()
